package com.kstech.mp3604.fragments

import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.kstech.mp3604.base.BaseDialogFragment
import com.kstech.mp3604.base.Global
import com.kstech.mp3604.base.HomeViewModel
import com.kstech.mp3604.databinding.FragmentIpPortSettingBinding

class DialogIpPortSettingFragment() :
    BaseDialogFragment<FragmentIpPortSettingBinding>(FragmentIpPortSettingBinding::inflate) {

    private lateinit var mViewModel: HomeViewModel
    override fun onInitView() {
        mViewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]
        binding.apply {
            val sp_ip = SPUtils.getInstance().getString(Global.SETTING_IP)
            val sp_port = SPUtils.getInstance().getInt(Global.SETTING_PORT)
            if (!sp_ip.isNullOrEmpty()) {
                ipedt.setText(sp_ip)
            }
            if (sp_port != -1) {
                portedt.setText(sp_port.toString())
            }
            submit.setOnClickListener {
                val ip = ipedt.text.toString().trim()
                val port = portedt.text.toString().trim()
                if (checkIpValid(ip) && checkPortValid(port)) {
                    SPUtils.getInstance().put(Global.SETTING_IP, ip)
                    SPUtils.getInstance().put(Global.SETTING_PORT, port.toInt())
                    requireActivity().finish()
                } else {
                    mViewModel.ipPortSettingListener.ipIsInValid()
                }
                dialog!!.cancel()
            }
            closeDialog.setOnClickListener {
                dialog!!.cancel()
            }
        }
    }

    private fun checkPortValid(port: String): Boolean {
        return port.toIntOrNull() != null
    }


    private fun checkIpValid(ip: String): Boolean {
        val ipv4Pattern =
            """^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$""".toRegex()
        return ipv4Pattern.matches(ip)
    }
}